package com.fengdi.solutions.esay;

import java.util.Stack;


/**
 * @author FengDi
 * @Title 232. 用栈实现队列
 * @Description  请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作
 * @Solution 由于栈是先进后出，而队列是一种先进先出的结构，因此在进行出队操作时，栈底元素实际上是队头元素。因此我们需要准备两个栈，在进行出队及
 *           获取队头元素时实际是对逆序栈的栈顶元素进行操作。而进队操作是在源栈中直接入栈即可。
 * */
public class _232_useStackRealizeQueue {
    private final Stack<Integer> stack_initial = new Stack<>();
    private final Stack<Integer> stack_reverse = new Stack<>();

    public void push(int x) {
        if(this.stack_reverse.isEmpty() && this.stack_initial.isEmpty()) {
            this.stack_initial.push(x);
        }else if(this.stack_initial.isEmpty()) {
            this.changeStack(this.stack_reverse, this.stack_initial);
            this.stack_initial.push(x);
        }else {
            this.stack_initial.push(x);
        }
    }

    public int pop() {
        if(this.stack_reverse.isEmpty() && this.stack_initial.isEmpty()) {
            return -1;
        }

        if (this.stack_reverse.isEmpty()) {
            this.changeStack(this.stack_initial, this.stack_reverse);
        }
        return this.stack_reverse.pop();
    }

    public int peek() {
        if(this.stack_reverse.isEmpty() && this.stack_initial.isEmpty()) {
            return -1;
        }

        if (this.stack_reverse.isEmpty()) {
            this.changeStack(this.stack_initial, this.stack_reverse);
        }
        return this.stack_reverse.peek();
    }

    public boolean empty() {
        return this.stack_reverse.isEmpty() && this.stack_initial.isEmpty();
    }

    /**
     * @author FengDi
     * @Description
     * @param from 源栈
     * @param to 目标栈
     * */

    private void changeStack(Stack<Integer> from, Stack<Integer> to) {
        while (!from.isEmpty()) {
            to.push(from.pop());
        }
    }
}
